﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Globalization;

namespace Project_Proto
{
    class FileControl
    {
        public static string rootPath;

        public string Gruppenname
        { 
            get; 
            private set; 
        }
        public string Titel
        {
            get;
            private set;
        }
        public DateTime Datum
        {
            get;
            private set;
        }


        /// <summary>
        /// This is the constructor...it does pretty much nothing except creating a FileControl.
        /// You shouldn't use this I think...
        /// </summary>
        public FileControl()
        {

        }


        public static string GroupFilter = "";
        public static string TitelFilter = "";
        public static DateTime DatumVon = DateTime.MinValue;
        public static DateTime DatumBis = DateTime.MaxValue;

        /// <summary>
        /// FileControl.GroupFilter needs to be set.
        /// Use FileControl.listAvailableGroups() to get all possible Values.
        /// 
        /// Also Filter with:
        /// FileControl.TitleFilter != ""
        /// FileControl.DateFrom != DateTime.MinValue
        /// FileControl.DateTo != DateTime.MaxValue
        /// </summary>
        /// <returns>null if FileControl.GroupFilter is not setCorrectly, empty List if no results, List of FileControl objects</returns>
        public static List<FileControl> search()
        {
            List<FileControl> res = new List<FileControl>();

            string searchpath = rootPath;

            if (FileControl.listAvailableGroups().Contains(FileControl.GroupFilter))
            {
                searchpath += "\\" + GroupFilter;
            }
            else
            {
                return null;
            }

            List<string> filenames = Directory.GetFiles(searchpath).ToList();

            foreach (string filename in filenames)
            {
                if (filename.Contains(".lehrer"))
                {
                    //break;
                }
                else
                {
                    string f = filename.Split('.').First();
                    f = filename.Split('\\').Last();
                    string year = f.Substring(0, 4);
                    string month = f.Substring(4, 2);
                    string day = f.Substring(6, 2);
                    DateTime t = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day));
                    string title = f.Split('-').Last();
                    if (t > FileControl.DatumVon && t < FileControl.DatumBis && title.Contains(FileControl.TitelFilter))
                    {
                        FileControl fc = new FileControl();
                        fc.Datum = t;
                        fc.Gruppenname = FileControl.GroupFilter;
                        fc.Titel = f.Substring(9).Split('.').First();
                        res.Add(fc);
                    }
                }
            }

            return res;
        }

        public static void resetFilter()
        {
            FileControl.GroupFilter = "";
            FileControl.TitelFilter = "";
            FileControl.DatumVon = DateTime.MinValue;
            FileControl.DatumBis = DateTime.MaxValue;
        }

        public static string getFullPathFor(string group, DateTime dt, string title)
        {
            string res = FileControl.rootPath + "\\";
            res += group + "\\";
            res += dt.Year.ToString() + (dt.Month < 10 ? "0" + dt.Month.ToString() : dt.Month.ToString()) + (dt.Day < 10 ? "0" + dt.Day.ToString() : dt.Day.ToString());
            res += "-" + title.Replace(' ', '_').Replace('-', '_');
            res += ".pdf";
            return res;
        }

        public static List<String> listAvailableGroups()
        {
            List<string> dirPaths = Directory.GetDirectories(rootPath).ToList();
            List<string> res = new List<string>();
            foreach (string p in dirPaths)
            {
                res.Add(p.Split('\\').ToList().Last());
            }
            return res;
        }

        /// <summary>
        /// Opens File in default PDF Viewer
        /// </summary>
        /// <returns>true if successful; false if error</returns>
        public bool openFile()
        {
            string fullPath = FileControl.getFullPathFor(this.Gruppenname, this.Datum, this.Titel);
            string path = FileControl.rootPath + "\\" + this.Gruppenname;
            var processStartInfo = new ProcessStartInfo();
            processStartInfo.WorkingDirectory = path;
            processStartInfo.FileName = fullPath.Split('\\').Last();


            Process.Start(processStartInfo);

            return true;

        }

        public static List<string> getLehrerForGroup(string group)
        {
            var file = File.Open(FileControl.rootPath + "\\" + group + "\\" + ".lehrer", FileMode.OpenOrCreate);
            if (file == null)
            {
                return null;
            }
            if (!file.CanRead)
            {
                return null;
            }
            string buf = "";
            while (file.Position < file.Length)
                buf += Convert.ToChar(file.ReadByte());
            long fl = file.Length;
            file.Close();
            if (fl>1)
            {
                return buf.Replace("\r", "").Split('\n').ToList();
            }
            else
            {
                return new List<string>();
            }
        }

        /// <summary>
        /// Writes the Groupmembers to the file, creates File if neccessary.
        /// </summary>
        /// <param name="lehrer"></param>
        /// <param name="group"></param>
        /// <returns>true if success; false if failed (wrong path, no permission,etc)</returns>

        public static bool setLehrerForGroup(List<string> lehrer, string group)
        {
            var file = File.Open(FileControl.rootPath + "\\" + group + "\\" + ".lehrer", FileMode.Create);

            if (file == null)
            {
                return false;
            }
            if (!file.CanWrite)
            {
                return false;
            }
            file.Position = 0;
            bool isFirst = true;
            foreach (string l in lehrer)
            {
                if (isFirst)
                {
                    isFirst = false;
                }
                else
                {
                    file.WriteByte(Convert.ToByte('\r'));
                    file.WriteByte(Convert.ToByte('\n'));
                }
                foreach (char c in l)
                {
                    file.WriteByte(Convert.ToByte(c));
                }

            }
            file.Close();
            return true;
        }

        /* * TOPS * */
        public static List<TagesordnungspunktObjekt> searchTOPS(string suchbegriff)
        {
            TOPWrapper tw = FileControl.getTOPWrapper();

            var topFilter =
            from top in tw.tops
            where (top.beschluss.Contains(suchbegriff) || top.bezeichnung.Contains(suchbegriff)) && top.gruppe == FileControl.GroupFilter
            select top;

            return topFilter.ToList();
        }

        public static bool addTOP(TagesordnungspunktObjekt top)
        {
            TOPWrapper tw = FileControl.getTOPWrapper();

            tw.tops.Add(top);
            return FileControl.writeTOPWrapper(tw);

        }

        public static List<TagesordnungspunktObjekt> getAllTOPS()
        {
            TOPWrapper tw = FileControl.getTOPWrapper();

            return tw.tops;

        }

        private static TOPWrapper getTOPWrapper()
        {
            XMlSerializer<TOPWrapper> ser =
            new XMlSerializer<TOPWrapper>();

            FileStream fs = new FileStream(string.Format(CultureInfo.InvariantCulture, FileControl.rootPath + "\\.beschlussliste"), FileMode.OpenOrCreate);

            TOPWrapper topwrap = ser.Deserialize(fs);

            fs.Close();
            if (topwrap == null)
            {
                return new TOPWrapper();

            }

            return topwrap;
        }

        //public List<TagesordnungspunktObjekt> tops;
        public static void openPDFforTOP(TagesordnungspunktObjekt top)
        {
            string fullPath = FileControl.getFullPathFor(top.gruppe, top.datum, top.protokolltitel);
            string path = FileControl.rootPath + "\\" + top.gruppe;
            var processStartInfo = new ProcessStartInfo();
            processStartInfo.WorkingDirectory = path;
            processStartInfo.FileName = fullPath.Split('\\').Last();


            Process.Start(processStartInfo);

            //return true;
        }

        private static bool writeTOPWrapper(TOPWrapper tw)
        {
            XMlSerializer<TOPWrapper> ser =
            new XMlSerializer<TOPWrapper>();

            FileStream fs = new FileStream(string.Format(CultureInfo.InvariantCulture, FileControl.rootPath + "\\.beschlussliste"), FileMode.OpenOrCreate);

            ser.Serialize(fs, tw);

            fs.Close();

            return true;
        }

        /* * ZWISCHENSPEICHERN * */

        public static BerichtObjekt QuickLoad(string path)
        {
            XMlSerializer<BerichtObjekt> ser =
            new XMlSerializer<BerichtObjekt>();

            FileStream fs = new FileStream(path, FileMode.OpenOrCreate);

            BerichtObjekt bericht = ser.Deserialize(fs);

            fs.Close();
            if (bericht == null)
            {
                return new BerichtObjekt();

            }

            return bericht;
        }

        public static void QuickSave(string path, BerichtObjekt b)
        {
            XMlSerializer<BerichtObjekt> ser =
            new XMlSerializer<BerichtObjekt>();

            FileStream fs = new FileStream(path, FileMode.OpenOrCreate);

            ser.Serialize(fs, b);

            fs.Close();
        }

        
    }
    public class TOPWrapper
    {
        public List<TagesordnungspunktObjekt> tops = new List<TagesordnungspunktObjekt>();
    }
}
